<template>
  <div class="bread-crumb-box">
    <span v-for="(item, index) in breadcrumbList" :key="index">
      <label class="separator">/</label>
      <span :class="breadcrumbList.length - 1 === index ? 'crumb-last' : 'crumb'" @click="pathTo(item)">
        {{ item.name }}
      </span>
    </span>
  </div>
</template>

<script setup lang="ts">
import {reactive, watch} from "vue"
import {useRouter} from "vue-router";

const router = useRouter() // 定义路由

let breadcrumbList: any = reactive([])

// 路径跳转
function pathTo(item: any) {
  if (item.path) {
    router.push(item.path)
  }
}

// 监听路由变化
watch(() => router.currentRoute.value, (val) => {
  breadcrumbList.length = 0
  val.matched.forEach(item => {
    if (item.name) {
      breadcrumbList.push(item)
    }
  })
  if (val.params.name) {
    breadcrumbList[breadcrumbList.length - 1].name = val.params.name
  }
}, {deep: true, immediate: true})
</script>

<style scoped lang="less">
.bread-crumb-box {
  height: 34px;
  line-height: 34px;

  .separator {
    margin: 0 5px;
    color: #606266;
  }

  .crumb {
    font-size: 14px;
    font-weight: 400;
    color: #606266;
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }

  .crumb-last {
    font-weight: 700;
    color: #303133;
    font-size: 14px;
  }
}
</style>